#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include "../include/meta.h"
#include "../include/vfs_errorcodes.h"
//listfile (file_path, output_file) - Extract the contents of a file specified by <file_path> and store in output file.

char* list_file(char* file_path,char* output_file)
{
	char result[100];
	int index; 
	if(root==NULL)
	{	
		strcpy(result,"listfile_FAILURE ");
		strcat(result,ERR_VFS_LISTFILE_04);
		sprintf(str, "%s",result);
		return str;
	}
	//displayBstTree(bstroot);
	index=bst_search(bstroot,file_path);
	if(index==-1)
	{
		strcpy(result,"listfile_FAILURE ");
		strcat(result,ERR_VFS_LISTFILE_01);
		sprintf(str, "%s",result);
		return str;	
	}
	
	//printf("%s,%s",file_path,output_file);
	//char *ext= strrchr(file_path,'.');
	//char *str12= ext+1; 	
	
	//char *ext1= strrchr(output_file,'.');
	//char *str1= ext1+1; 
	//printf("%s,%s\n",str12,str1);
	//if(str12!=NULL && str1!=NULL)
	//{
	//if(stcmp(str12,"")
	//if(strcmp(str12,"txt")!=0)
	if(strcmp(fd[index].file_type,"text"))
	{
		strcpy(result,"listfile_FAILURE ");
		strcat(result,ERR_VFS_LISTFILE_02);
		sprintf(str, "%s",result);
		return str; 		
	}
	//}
	int offset = main_header_var->headersize + 1024*(fd[index].block_number);
	//printf("offset in list:%d",offset);
	FILE *fout, *fp;
	fp=fopen(mounted_vfs,"rb+");
	fout=fopen(output_file,"w");	
	fseek(fp,offset,SEEK_SET);
	char buffer[1024];

	if(fp==NULL)
	{	
		strcpy(result,"listfile_FAILURE ");
		strcat(result,ERR_VFS_LISTFILE_01);
		sprintf(str, "%s",result);
		return str;
	}

	if(fout==NULL)
	{
		strcpy(result,"listfile_FAILURE ");
		strcat(result,ERR_VFS_LISTFILE_03);
		sprintf(str, "%s",result);
		return str;
	}

	int size= fd[index].file_size; //printf("list: %d, %d\n",index,size);
	char ch; int x;
	while((x= ftell(fout))<size)
	{		//printf("%d ",x);
			ch= fgetc(fp); //printf("%c",ch);
			fputc(ch,fout);
	}

	fclose(fp);
	fclose(fout);
	
	return "listfile_SUCCESS";
}


